package com.hcss.qywechat.user.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.hcss.common.util.EncipherUtil;
import com.hcss.paging.constant.PagingConstant;
import com.hcss.paging.model.QuerySchema;
import com.hcss.qywechat.user.constant.WQyUserConstants;
import com.hcss.qywechat.user.model.WQyUser;
import com.hcss.qywechat.user.model.par.WQyUserPar;
import com.hcss.qywechat.user.model.vo.WQyUserVO;
import com.hcss.qywechat.user.service.WQyUserService;
import com.hcss.sys.role.model.HcSysRoleuser;
import com.hcss.sys.role.service.RoleService;
import com.hcss.update.model.UpdateSchema;
import com.hcss.util.AjaxResult;
import com.hcss.util.BeanCopyUtil;
import com.hcss.util.EmptyUtil;
import com.hcss.util.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @描述: WQyUser 功能模块
 * @作者: fangtao
 * @创建日期: 2019-11-05 10:35:55
 */
@Slf4j
@RestController
@RequestMapping("wQyUser")
public class WQyUserController {

	@Autowired
	private RoleService roleService;
	@Autowired
    private WQyUserService wQyUserService;

    /**
     * 查询使用的schema
     * 使用.withQueryFields(QueryType type, String... queryFileds)插入查询规则和查询字段
     */
    static QuerySchema querySchema = new QuerySchema(WQyUser.class);

	/**
	 * 更新插入的schema，用于鉴定数据的安全性
	 */
    static UpdateSchema updateSchema = new UpdateSchema(WQyUser.class, null, null);

	/**
	 * WQyUser数据列表页面
     *
	 * @return
	 */
	@GetMapping("listPage")
	public ModelAndView listPage(){
		return new ModelAndView("/sys/user/user-listPage");
	}
	
	/**
	 * 新增页面
	 * @return
	 */
	@GetMapping("/addorupdate")
	public ModelAndView addPage(){
		ModelAndView page = new ModelAndView("/wQyUser/wQyUser-addOrUpdatePage");
		return page;
	}
	
	/**
	 * 修改页面
	 * @param id
	 * @return
	 */
	@GetMapping("/addorupdate/{id}")
	public ModelAndView updatePage(@PathVariable("id") String id){
		ModelAndView page = new ModelAndView("/wQyUser/wQyUser-addOrUpdatePage");
		WQyUser wQyUser = wQyUserService.selectByPK(id);
        page.addObject("data", JSON.toJSONString(wQyUser));
		return page;
	}
	
	/**
     * WQyUser分页数据接口
     * @param model 带有查询参数的对象
     * @return
     */
	@RequestMapping("/list")
	public AjaxResult wQyUser(WQyUserVO model){
		model.setQuerySchema(querySchema);
        try {
        	if (model.getPagenation()) {
        		PageInfo<WQyUserVO> list = wQyUserService.queryPagingComplexData(model);
                return AjaxResult.getPageHelperTableResult(list);
        	} else {
        		List<WQyUserVO> list =  wQyUserService.queryAllComplexData(model);
        		return AjaxResult.getSuccessResult(list);
        	}
        } catch (Exception e) {
            log.error("数据查询出错，参数：" + model.toString(), e);
            return AjaxResult.getErrorResult(e.getMessage());
        }
	}
	
	/**
     * WQyUser 单个数据的获取
     * @param id WQyUser主键
     * @return
     */
	@GetMapping("/{id}")
	public AjaxResult getWQyUserById(@PathVariable("id") String id){
        WQyUser wQyUser = wQyUserService.selectByPK(id);
        return new AjaxResult(wQyUser);
	}
	
	/**
	 * WQyUser 的新增
	 * @param par
	 * @return
	 */
	@GetMapping
	public AjaxResult addWQyUser(WQyUserPar par) {
		if (!UpdateSchema.checkAddOrUpdate(par, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			WQyUser model = BeanCopyUtil.copyConvey(par, WQyUser.class);
			wQyUserService.insertModel(model);
            return new AjaxResult();
		} catch (Exception e) {
            log.error("新增操作出错，参数：[{}] ", par.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
	
	/**
	 * WQyUser 的修改
	 * @return
	 */
	@PutMapping("/{id}")
	public AjaxResult updateWQyUser(@PathVariable("id") String id, WQyUserPar par) {
		if (!UpdateSchema.checkAddOrUpdate(par, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			WQyUser model = BeanCopyUtil.copyConvey(par, WQyUser.class);
            wQyUserService.updateModel(model);
            return new AjaxResult();
		} catch (Exception e) {
            log.error("更新操作出错，参数：[{}]", par.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
    }
    
    /**
	 * 根据ids集合进行删除
	 * 使用默认的分割符号“,”
	 * @param ids
	 * @return
	 */
	@DeleteMapping("/{ids}")
	public AjaxResult deleteByIds(@PathVariable("ids") String ids){
		if (EmptyUtil.isHaveEmpty(ids)) return AjaxResult.getMissingParamResult();
		try {
			List<Long> idList = ListUtil.convey(ListUtil.split(ids, PagingConstant.defaultSplit), Long.class);
			wQyUserService.deleteByIds(idList);
            return new AjaxResult();
		} catch (Exception e) {
            log.error("批量删除出错，参数：[{}]",ids, e);
            return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * WQyUser新增或修改数据接口
	 * @param model 数据对象
	 * @return
	 */
	@RequestMapping("/addOrUpdate")
		public AjaxResult addOrUpdate(WQyUserVO model){
		if (!UpdateSchema.checkAddOrUpdate(model, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			if (!wQyUserService.checkCodeUnique(model)) {
				return AjaxResult.getErrorResult("用户[" + model.getUserid() + "]已存在");
			}
			//MD5加密
			if (!EmptyUtil.isHaveEmpty(model.getPassword())) {
				model.setPassword(EncipherUtil.md5(model.getPassword()));
			}
			if (EmptyUtil.isHaveEmpty(model.getId())) {
				//在这里做出改变
				wQyUserService.insertModel(model);
				//赋予权限
				String id=model.getUserid();
				HcSysRoleuser hcSysRoleuser=new HcSysRoleuser( );
				hcSysRoleuser.setRoleid( "1ef80a0cfdfc48b0b7081654ad28d379" );
				hcSysRoleuser.setUserid( id );
				roleService.saveRoleUser(hcSysRoleuser);
			}
			return new AjaxResult(model.getId());
		} catch (Exception e) {
			log.error("新增或更新操作出错，参数：" + model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
	/**
	 * WQyUser重置密码
	 * @param model 数据对象
	 * @return
	 */
	@RequestMapping("/resetWord")
	public AjaxResult resetPassword(WQyUserVO model){
		if (!UpdateSchema.checkAddOrUpdate(model, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			//MD5加密
			model.setPassword(EncipherUtil.md5("KeLe1234567"));
			wQyUserService.resetPassword(model);
			return new AjaxResult();
		} catch (Exception e) {
			log.error("新增或更新操作出错，参数：" + model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
	/**
	 * 根据id获取关联货代的用户信息
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail")
	public AjaxResult detail(Long id) {
		if (EmptyUtil.isHaveEmpty(id))
			return AjaxResult.getMissingParamResult();
		try {
			WQyUserVO wQyUserVO = wQyUserService.selectDataById(id);
			return new AjaxResult(wQyUserVO);
		} catch (Exception e) {
			log.error("根据用户ID获取用户信息失败", e.getMessage());
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 删除用户、关联货代、所属机场
	 * @param model
	 * @return
	 */
	@RequestMapping("/deleteComplexData")
	public AjaxResult deleteComplexData(WQyUserVO model) {
		try {
			wQyUserService.deleteComplexData(model);
			return new AjaxResult();
		} catch (Exception e) {
			log.error("删除用户及相关货代、机场信息失败", e.getMessage());
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 修改密码
	 * @param oldWord 旧密码
	 * @param newWord 新密码
	 * @param confirmWord 确认密码
	 * @param id 用户表id
	 * @return
	 */
	@RequestMapping("/updateWord")
	public AjaxResult updateWord(String oldWord,String newWord,String confirmWord,Long id) {
		if (EmptyUtil.isHaveEmpty(oldWord, newWord, confirmWord,id)) {
			return AjaxResult.getMissingParamResult();
		}
		if (!newWord.equals(confirmWord)) {
			return AjaxResult.getErrorResult(WQyUserConstants.editPasswordCheck.WORD_NOTEQ);
		}
		WQyUser wQyUser =wQyUserService.selectByPK(id.toString());
		try {
			//校验原始密码是否正确
			if (!EncipherUtil.md5(oldWord).equals(wQyUser.getPassword())) {
				return AjaxResult.getErrorResult(WQyUserConstants.editPasswordCheck.ERROR_ORI_WORD);
			}
			//校验新密码与用户旧密码
			if (EncipherUtil.md5(newWord).equals(wQyUser.getPassword())) {
				return AjaxResult.getErrorResult(WQyUserConstants.editPasswordCheck.REPEAT_WORD);
			}
			wQyUser.setPassword(EncipherUtil.md5(newWord)); //更新密码
			wQyUserService.updateModel(wQyUser);
			return new AjaxResult(AjaxResult.codeDefault, AjaxResult.msgDefault);
		} catch (Exception e) {
			log.error("获取所有用户失败", e.getMessage());
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

}